<template>
  <div class="chat-container">
    <Header />
    <div class="chat-content-area">
      <div v-if="showWelcome" class="welcome-container">
        <div class="welcome-card">
          <div class="welcome-avatar">
            <img src="@/static/u948.png" alt="AI助手头像" />
          </div>
          <h3 class="welcome-title">网优AI助手</h3>
          <p class="welcome-desc">
            你好，我是你的专属AI助手，我可以提供指标<br />
            查询，网管指令操作，智能报表分析输出，<br />
            还有很多很多功能待你发现。<br />
            你想问点什么呢？尽管问我哈！！
          </p>
        </div>
      </div>
      <BubbleList
          v-else
          :list="list"
          max-height="calc(100vh - 240rpx)"
          :always-show-scrollbar="alwaysShowScrollbar"
          :btn-color="btnColor"
          :btn-loading="btnLoading"
          :back-button-position="backButtonPosition"
          :btn-icon-size="btnSize"
      />
    </div>
    <div class="sender-wrapper" @click="hideWelcome">
      <Sender v-model="senderValue" clearable allow-speech />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import type { BubbleListItemProps, BubbleListProps } from 'vue-element-plus-x/types/components/BubbleList/types';
import Header from '@/components/header/index.vue';

const senderValue = ref('');
const showWelcome = ref(true);

type listType = BubbleListItemProps & {
  key: number;
  role: 'user' | 'ai';
};

const list = ref<listType[]>([]);
const alwaysShowScrollbar = ref(false);
const btnLoading = ref(true);
const bottomValue = ref(10);
const leftValue = ref(600);
const backButtonPosition = computed(() => {
  return {
    bottom: `${bottomValue.value}rpx`,
    left: `${leftValue.value}rpx`,
  };
});
const btnColor = ref('#2D38FF');
const btnSize = ref(30);

const hideWelcome = () => {
  if (showWelcome.value) {
    showWelcome.value = false;
    // initChat();
  }
};

const initChat = () => {
  const welcomeMsg = generateFakeItems(1);
  list.value.push(...welcomeMsg);
  setTimeout(() => {
    btnLoading.value = false;
  }, 500);
};

function generateFakeItems(count: number): listType[] {
  const messages: listType[] = [];
  for (let i = 0; i < count; i++) {
    const role = 'ai';
    const placement = 'start';
    const key = i + 1;
    const content = '💖 您好！点击输入框开始聊天，我可以帮您解决网络优化问题～';
    const loading = false;
    const shape = 'corner';
    const variant = 'filled';
    const isMarkdown = false;
    const typing = false;
    const avatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';

    messages.push({
      key,
      role,
      placement,
      content,
      loading,
      shape,
      variant,
      isMarkdown,
      typing,
      isFog: true,
      avatar,
      avatarSize: '48px',
      avatarGap: '6px',
    });
  }
  return messages;
}


// 监听自定义事件
const handleChatMessagesFetched = (messages) => {
  console.log("开始了")
  hideWelcome()
  const formattedMessages = messages.map((message, index) => {
    const parsedMessage = JSON.parse(message.message);
    return {
      key: message.id,
      role: message.role === 'user' ? 'user' : 'ai',
      placement: message.role === 'user' ? 'end' : 'start',
      content: parsedMessage.content,
      loading: false,
      shape: 'corner',
      variant: 'filled',
      isMarkdown: false,
      typing: false,
      isFog: false,
      avatar: message.role === 'user' ? 'user-avatar-url' : 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
      avatarSize: '48px',
      avatarGap: '6px',
    };
  });
  list.value = formattedMessages;
};

onMounted(() => {
  showWelcome.value = true;

  uni.$on('chatMessagesFetched', handleChatMessagesFetched);

});

// 组件卸载时取消监听
onUnmounted(() => {
  uni.$off('chatMessagesFetched', handleChatMessagesFetched);
});
</script>

<style>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding-left: 24rpx;
  padding-right: 24rpx;
  position: relative;
  background: transparent;
}

/* 聊天内容区域 */
.chat-content-area {
  position: relative;
  flex: 1;
  background: transparent;
  overflow-y: auto;
}

/* 欢迎组件（带头像） */
.welcome-container {
  position: absolute;
  top: 20px;
  left: 20px;
  right: 20px;
  display: flex;
  justify-content: center;
  background: transparent;
}

.welcome-card {
  background-color: white;
  padding: 60rpx 40rpx 40rpx; /* 顶部留出头像空间 */
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  max-width: 600rpx;
  width: 100%;
  text-align: center;
}

/* 头像样式 */
.welcome-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%; /* 圆形效果 */
  overflow: hidden; /* 隐藏超出部分 */
  margin: 0 auto 20rpx; /* 居中 + 底部间距 */
}
.welcome-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持图片比例 */
}

/* 标题样式 */
.welcome-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10rpx; /* 与头像的间距 */
}

/* 描述文字样式 */
.welcome-desc {
  font-size: 24rpx;
  color: #606266;
  margin-bottom: 30rpx;
  line-height: 1.6; /* 优化行间距 */
  white-space: pre-line; /* 解析<br>换行 */
}

/* 发送框样式（不变） */
.sender-wrapper {
  padding: 16rpx 0;
  background: #FFFFFF;
  border-top: 1px solid #ECECEC;
  z-index: 10;
  cursor: pointer;
}

/* 消息列表样式（不变） */
:deep(.el-bubble-list) {
  width: 100%;
}
</style>